<template>
  <div>
    <el-card>
      <div id="containerWeather"></div>
    </el-card>

    <!-- 显示天气信息的窗体 -->

    <!--  
    <el-dialog v-model="weatherDialogVisible" title="天气情况" width="30%">
       
      <div>
        <h4>城市：{{ weatherInfo.province + weatherInfo.city }}</h4>
        <h4>播报时间：{{ weatherInfo.reporttime }}</h4>
        <h4>大气温度：{{ weatherInfo.temperature }}</h4>
        <h4>天气: {{ weatherInfo.weather }}</h4>
        <h4>风向：{{ weatherInfo.winddirection }}</h4>
        <h4>风力：{{ weatherInfo.windpower }}</h4>
      </div>
    </el-dialog> -->

    <!-- 表格展示数据信息 -->
    <el-table :data="weatherInfo" id="wentherInfoTable">
      <el-table-column prop="province" label="省份" width="180" />
      <el-table-column prop="city" label="行政区" width="180" />
      <el-table-column prop="weather" label="天气情况" />
      <el-table-column prop="temperature" label="气温" />
      <el-table-column prop="winddirection" label="风向" />
      <el-table-column prop="windpower" label="风力" />
      <el-table-column prop="reporttime" label="播报时间" />
    </el-table>

    <!-- 根据城市查询天气的输入框 -->
    <el-card id="city_input">
      <el-input v-model="city" placeholder="请输入辖区名称" />

      <el-button type="primary" id="city_btn" @click="getWeather()"
        >搜索</el-button
      >
    </el-card>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef } from "@vue/reactivity";
import { weatherReq } from "@/networks/weatherReq.js";
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
export default {
  name: "weather",
  setup(context, props) {
    window._AMapSecurityConfig = {
      securityJsCode: "7a147469fc71afc2c2540196e2453b2b",
    };
    const map = shallowRef(null);
    let weatherInfo = reactive([
      {
        province: null,
        city: null,
        weather: null,
        temperature: null,
        winddirection: null,
        windpower: null,
        reporttime: null,
      },
    ]);
    // let weatherDialogVisible = ref(false);
    let city = ref("合肥市");
    let searchPoint = reactive([117.230981, 31.843352]);
    // 获取天气数据的函数

    return {
      // weatherDialogVisible,
      map,
      weatherInfo,
      city,
      searchPoint,
    };
  },
  methods: {
    initMap() {
      this.map?.destroy(); //网上查的
      this.map?.clearMap(); //官方文档，清除所有覆盖物
      let instance = this;
      AMapLoader.load({
        key: "2b45c6a7655404e69a9b856504d8625c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      })
        .then((AMap) => {
          this.map = new AMap.Map("containerWeather", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: instance.searchPoint, //初始化地图中心点位置
            mapStyle: "amap://styles/45311ae996a8bea0da10ad5151f72979",
            mapStyle: "amap://styles/dark",
          });
          // 导入插件
          AMap.plugin(
            [
              "AMap.ToolBar",
              "AMap.Scale",
              "AMap.HawkEye",
              "AMap.MapType",
              "AMap.Geolocation",
              "AMap.DistrictSearch",
            ],
            async function () {
              // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
              instance.map.addControl(new AMap.ToolBar());
              // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
              instance.map.addControl(new AMap.HawkEye({ isOpen: true }));
              // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
              instance.map.addControl(new AMap.MapType());
              // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
              instance.map.addControl(new AMap.Geolocation());
              // console.log("插件安装");
              let district = new AMap.DistrictSearch({
                // 返回行政区边界坐标等具体信息
                extensions: "all",
                // 设置查询行政区级别为 区
                level: "street",
              });
              district.search(
                instance.city,
                await function (status, result) {
                  // 获取该地区的边界信息
                  try {
                    if(result?.districtList == null)
                    {
                      return ElMessage.error("获取边界数据失败");
                    }
                    let bounds = result?.districtList[0]?.boundaries;
                    let polygons = [];
                    // console.log(bounds);
                    if (bounds) {
                      for (let i = 0, l = bounds.length; i < l; i++) {
                        //生成行政区划polygon
                        let polygon = new AMap.Polygon({
                          map: instance.map,
                          strokeWeight: 1,
                          path: bounds[i],
                          fillOpacity: 0.7,
                          fillColor: "#F56C6C",
                          strokeColor: "#CC66CC",
                        });
                        polygons.push(polygon);
                        // console.log(instance.city);
                      }
                      // 地图自适应
                      instance.map.setFitView();
                    }
                  } catch (err) {
                    console.log(err);
                  }
                }
              );
            }
          );

          //   注册地图点击事件
          this.map.on("click", async (e) => {
            const lnglat = e.lnglat;
            const { data: res } = await weatherReq({
              lng: lnglat.lng,
              lat: lnglat.lat,
            });
            try {
              //获取点击地图位置城市的结构化名称
              const { data: city } = await axios.get(
                `https://restapi.amap.com/v3/geocode/regeo?key=f58766337111f56d9101db384fbea982&location=${lnglat.lng},${lnglat.lat}`
              );
              // console.log(city);
              instance.city = city.regeocode.addressComponent.district;
            } catch (err) {
              console.log(err);
            }

            // res中存储了当地的天气信息
            // console.log(res);
            instance.weatherInfo[0] = res;
            // console.log(instance.weatherInfo);
            this.map.destroy();
            this.initMap();
            // instance.weatherDialogVisible = true;
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },

    async getWeather() {
      let instance = this;
      try {
        //尝试获取地理编码
        const { data: res } = await axios.get(
          `https://restapi.amap.com/v3/geocode/geo?key=f58766337111f56d9101db384fbea982&address=${instance.city}`
        );
        const cityPoint = res.geocodes[0].location.split(",");
        // console.log(cityPoint);
        instance.searchPoint = cityPoint;
        const { data: cityWeather } = await weatherReq({
          lng: cityPoint[0],
          lat: cityPoint[1],
        });
        instance.weatherInfo[0] = cityWeather;
        // Object.assign(instance.weatherInfo, cityWeather);
        // console.log(instance.weatherInfo);
      } catch (err) {
        console.log(err);
        ElMessage.error(err);
      }
      this.map.destroy();
      this.initMap();
      this.weatherDialogVisible = true;
    },
  },
  activated() {
    // 页面活动时加载地图容器
    this.initMap();
  },
  deactivated() {
    //页面失去焦点后删除地图容器
    this.map.destroy();
    this.map.clearMap();
  },
};
</script>

<style lang="less" scoped>

#containerWeather {
  width: calc(100vw - 200px);
  height: calc(100vh - 7rem);
  position: absolute;
  top: 3rem;
  left: 200px;
}

#city_input {
  // display: flex;
  // justify-content: center;
  // align-items: center;
  position: absolute;
  z-index: 10;
  top: 5rem;
  left: 220px;
}

#city_btn {
  margin: 5px 35%;
}

#wentherInfoTable {
  position: absolute;
  bottom: 0px;
  width: calc(100vw - 200px);
  height: 4rem;
  
}


</style>
